<!--
    @Title: merge
    @Author  dudalei
    @Package
    @Date  2025/5/10 00:39
    @description:
-->
<script setup lang="ts">
import { inject } from 'vue'
import { AmapAndThreeInjectKey } from '@/components/AmapThree/index.ts'
const props = defineProps({
  center: {
    default: [0, 0],
  },
})

const mapStore = inject(AmapAndThreeInjectKey)
mapStore?.setup(({ camera, renderer, scene, map, aMap }) => {
  /**
   * 执行状态 用于防止重复渲染
   */
  let isRender = false
  let oldWidth = 0
  let oldHeight = 0
  let olddevicePixelRatio = window.devicePixelRatio
  renderer.setPixelRatio(window.devicePixelRatio)
  // renderer.value.autoClear = false
  const customCoords = map.customCoords
  const customLayer = new aMap.CustomLayer(renderer.domElement, {
    zIndex: 10,
    render: () => {
      // 如果正在执行则返回
      if (isRender) {
        return
      }
      // 表示正在执行渲染
      isRender = true
      renderer.resetState()
      mapStore._renders.forEach(async (fn) => {
        fn()
      })
      const { width, height } = map.canvas as HTMLCanvasElement
      // 动态更新three画布大小 这里做个判断和上次对比,变化了才设置
      if (olddevicePixelRatio !== window.devicePixelRatio) {
        olddevicePixelRatio = window.devicePixelRatio
        renderer.setPixelRatio(window.devicePixelRatio)
      }
      if (width !== oldWidth || height !== oldHeight) {
        oldWidth = width
        oldHeight = height
        camera.aspect = width / height
        camera.updateProjectionMatrix()
        renderer.setSize(width, height, true)
      }

      customCoords.setCenter(props.center)
      const { near, far, fov, up, lookAt, position } = customCoords.getCameraParams()
      // 这里的顺序不能颠倒，否则可能会出现绘制卡顿的效果。
      camera.near = near
      camera.far = far
      camera.fov = fov

      camera.position.set(...position)
      camera.up.set(...up)
      camera.lookAt(...lookAt)
      camera.updateProjectionMatrix()
      renderer.render(scene, camera)
      renderer.resetState()
      mapStore.map.render()
      // 执行完成 将执行状态 设置为false
      isRender = false
    },
    alwaysRender: true,
  })
  map.add(customLayer)
  // animate()
})

/**
 * 这里每帧更新画布
 */
function animate() {
  if (!mapStore) {
    return
  }
  mapStore.map.render()
  requestAnimationFrame(animate)
}
</script>

<template>
  <div v-if="false"></div>
</template>

<style scoped></style>
